<template>
    <van-row>
        <van-col span="2">
            <van-nav-bar left-arrow @click-left="onClickLeft" :border="false" />

        </van-col>
        <van-col span="2">
            <van-icon name="home-o" size="24px" style="margin-top: 10px; margin-left: 3px;" @click="onHome" />
        </van-col>
        <van-col span="16">
            <span style="margin-left: 102px; font-size: 18px; line-height: 45px; font-weight: 600;">搜索</span>
        </van-col>
        <van-col span="2">
            <van-icon name="search" size="24px" style="margin-top: 10px; margin-left: 3px;" />

        </van-col>
        <van-col span="2">
            <van-icon name="bars" size="24px" style="margin-top: 10px; margin-left: 3px;" />
        </van-col>
    </van-row>

    <van-search v-model="keyword" show-action wrap-with-form :clearable="true" placeholder="请输入搜索关键词" @search="onSearch"
        @input="handleInput">
        <template #action>
            <div @click="onClickButton">取消</div>
        </template>
    </van-search>


    <div class="container" v-if="keyword.trim()">
        <span style="border-bottom: 3px solid #9b9b0c; margin-left: 10px;">新车</span>
        <van-swipe-cell>
            <!-- <van-card
            price="35.18-49.98"
            desc="奔驰现优惠幅度比较大"
            title="北京奔驰-奔驰E级"
            class="goods-card"
            thumb="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
        /> -->
            <!--v-for=(别名，索引) in 源数组 :key= 是唯一标识-->
            <div style="margin-top: 10px;" v-for="(item, index) in productData" :key="index">
                <van-row>
                    <van-col span="7">
                        <img :src="item.carimg" alt="" width="100" height="80"
                            style="border-radius: 10px; margin-left: 5px;">
                    </van-col>
                    <van-col span="17">
                        <div style="margin-top: 18px;"></div>
                        <span>{{ item.carname }}</span><br>
                        <span>{{ item.minprice }}-{{ item.maxprice }}万</span>
                    </van-col>
                </van-row>
                <hr style="color: aliceblue;">
                </hr>
            </div>
            <!--如果没有数据 可以进行热门推荐 或展示暂无数据-->
            <div v-if="productData.length === 0">
                暂无搜索的数据结果
            </div>
        </van-swipe-cell>

    </div>
    <!-- 搜索历史记录 展示的地方 -->
    <div class="histroy-container" v-if="searchHistory.length">
        <div class="histoy-header">
            <p style="font-size: 12px; color: thistle; border-bottom: 3px solid yellow;">搜索历史</p>
            <div class="histroy-tags">
                <van-tag v-for="(item, index) in searchHistory" :key="index" closeable @close="deleteHistory(index)">
                    {{ item }}
                </van-tag>
            </div>
        </div>
        <!--清空全部的按钮 -->
        <van-button size="small" text @click="clearAllHistory">清空全部历史数据</van-button>
    </div>
    <div v-if="keyword.trim() == ''">
        <span
            style="font-size: 13px; border-bottom: 2px solid burlywood; color: #9b9b0c;padding-left: 5px; padding-right: 5px;">热门汽车</span>
        <van-grid :column-num="2" :border="false">
            <van-grid-item v-for="item in Carproduct" :key="item.id">
                <van-image width="100%" height="150" :src="item.carimg" />
                <div style="font-size: 14px;">{{ item.carname }}</div>
                <div style="font-size: 12px; color: red;">{{ item.minprice }}万起
                    <span style="padding-left: 5px; color: #868a8a;">询底价<van-icon name="play" /></span>
                </div>
                <div class="vbtn">
                    <van-button size="mini" type="warning" @click="onClick">质询服务</van-button> 
                    <van-button size="mini" type="danger" @click="onShoping">立即购买</van-button>
                </div>

            </van-grid-item>
        </van-grid>

    </div>
    <!-- <img :src="imgsrc" alt="" width="80" height="80"> -->
</template>

<script setup>

import { onMounted, ref, watch } from 'vue'
//引入router
import { useRouter } from 'vue-router'
//引入axios
// import axios from 'axios'
import { CarGoodsApi } from '../api'
const router = useRouter()
// const imgsrc = ref("https://img95.699pic.com/photo/50464/9776.jpg_wh860.jpg")
// 输入框中的value值
const keyword = ref('')
// 商品信息 模拟数据
const productData = ref([])

//定义搜索历史记录的变量 数组

const searchHistory = ref([])

// 监听事件
watch(keyword, (newVal) => {
    //去空格后的判断，有内容才执行搜索逻辑
    const keyword = newVal.trim()
    if (keyword) {
        //模拟接口数据
        mockSearch(keyword)
    } else {
        //g关闭关键词时，清空列表
        productData.value = []
    }
})

//模拟搜索接口  实际后台传输的时候进行切换 比如：api/search?keyword=奔驰E级

const mockSearch = (keyword) => {
    // axios({
    //     url: 'http://localhost:8080/api/search?carname=' + keyword,
    //     method: 'get'
    // }).then(res=>{
    //     console.log(res);

    // })
    // axios.get('http://localhost:8080/api/search?carname=' + keyword).then(res=>{
    //     console.log(res);

    // })


    // 后台 模拟传递过来的数据
    const mockdata = [
        //      { id: '101', name: '奔驰E', minprice: '35.18',maxprice:'49.98', imgsrc: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/9b08b1c3602645d7ad7574aeb71b6ce3~480x0.jpg' },
        // { id: '102', name: '奔驰s',  minprice: '135.18',maxprice:'149.98', imgsrc: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/9b08b1c3602645d7ad7574aeb71b6ce3~480x0.jpg' },
        // { id: '103', name: '奔驰c',  minprice: '15.18',maxprice:'19.98', imgsrc: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/e8abf034d5504085a9850c7b7632b065~480x0.jpg' },
        // { id: '104', name: '宝马-宝马3系',  minprice: '15.18',maxprice:'19.98', imgsrc: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/e8abf034d5504085a9850c7b7632b065~480x0.jpg' },
    ]
    CarGoodsApi.select.call({ carname: keyword }).then(res => {
        console.log(res);

        //    const filterres = res.filter(item =>{
        //         // toLowerCase() 忽略大小写，includes 判断是否包含某个字符串 C
        //         return item.carname.toLowerCase().includes(keyword.toLowerCase())
        //    } 
        //    )
        //     productData.value = filterres
        //      console.log('过滤后的数据:', filterres); // 检查是否有符合条件的结果
        productData.value = res.filter(item => item.carname.toLowerCase().includes(keyword.toLowerCase()))


    })

}
//定义推荐的商品
const Carproduct =ref()

onMounted(() => {
    CallCarProductApi()
})


const CallCarProductApi = () => {
    CarGoodsApi.select.call().then(res => {
        console.log(res);
        Carproduct.value = res
    })
}

// 保存历史记录到本地
const saveHistory = (keyword) => {
    //如果有重复的数据 直接移除掉，添加新的数据
    const index = searchHistory.value.indexOf(keyword)
    if (index !== -1) searchHistory.value.splice(index, 1)


    //每次新的搜索数据都放在最前方
    searchHistory.value.unshift(keyword)
    //限制 历史记录最多10条
    if (searchHistory.value.length > 10) {
        //删除最后一个元素
        searchHistory.value.pop()
    }
    //保存到本地
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

//点击图标跳转到首页
const onHome = () => {
    router.push('/')
}

//搜索
const onSearch = (val) => {
    console.log(val);
    const currentKeyword = val.trim()
    // 非空才保存
    if (currentKeyword) {
        // 添加搜索历史记录
        saveHistory(currentKeyword)
    }

};

// 处理搜索输入
const handleInput = () => {
    const currentKeyword = keyword.value.trim()
    if (currentKeyword === '') {
        productData.value = []
    }
}
const clearAllHistory = () => {
    searchHistory.value = []
    localStorage.removeItem('searchHistory')

}
const deleteHistory = (index) => {
    searchHistory.value.splice(index, 1)
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}


//取消按钮点击事件
const onClickButton = () => {
    console.log(keyword.value);
    keyword.value = ''

};

//咨询服务
const onClick = () => {
    alert('咨询服务,请问你是要咨询当前汽车吗？')
}

const onShoping = () => {
    alert('购买功能，即将跳转到购物页面')
}

//返回上一层页面
const onClickLeft = () => history.back();

</script>

<style scoped>
:deep(.van-nav-bar .van-icon) {
    color: black;
    font-size: 20px;
}

.histroy-tags {
    margin-top: 6px;
    margin-bottom: 6px;

    span {
        margin-right: 10px;
    }
}
.vbtn{
    margin-top: 3px;
}
</style>